package cn.mdmbct.douyin.common.storage;

import cn.mdmbct.douyin.common.bean.AccessToken;
import cn.mdmbct.douyin.common.bean.ClientToken;
import cn.mdmbct.douyin.common.bean.RefreshToken;
import cn.mdmbct.douyin.common.config.DyOpenApiConfig;
import cn.mdmbct.douyin.common.redis.DyRedisOps;
import com.alibaba.fastjson.JSONObject;

import java.util.concurrent.TimeUnit;

/**
 * redis配置存储管理器
 *
 * @author mdmbct  mdmbct@outlook.com
 * @date 2021/3/9 14:02
 * @modified mdmbct
 * @since 1.0
 */
public class RedisStorageManager extends BaseStorageManager {

    private final DyRedisOps redisOps;

    /**
     * 构造函数 顺便将配置存储redis
     *
     * @param redisOps redis操作
     */
    public RedisStorageManager(DyRedisOps redisOps, DyOpenApiConfig config) {
        super(config);
        this.redisOps = redisOps;
        saveOpenApiConfigToCache();
    }

    void saveOpenApiConfigToCache() {
        String s = JSONObject.toJSONString(openApiConfig);
        redisOps.setValue(openApiConfig.getConfigCacheKey(), s);
    }

    /**
     * 设置配置 同时保存配置至redis <p>
     *
     * @param config {@link DyOpenApiConfig}
     */
    @Override
    public void setOpenApiConfig(DyOpenApiConfig config) {
        super.setOpenApiConfig(config);
        saveOpenApiConfigToCache();
    }

    public DyOpenApiConfig getOpenApiConfigFromCache() {
        return redisOps.getValue(openApiConfig.getConfigCacheKey(), DyOpenApiConfig.class);
    }

    /**
     * 保存AccessToken token过期后自动被redis删除
     *
     * @param openId open id
     * @param token  AccessToken
     */
    @Override
    public void saveAccessToken(String openId, AccessToken token) {
        redisOps.setValue(accessTokenKey(openId), token, token.getExpireIn(), TimeUnit.MILLISECONDS);
    }

    @Override
    public AccessToken getAccessToken(String openId) {
        return redisOps.getValue(accessTokenKey(openId), AccessToken.class);
    }

    /**
     * 保存RefreshToken token过期后自动被redis删除
     *
     * @param openId open id
     * @param token  RefreshToken
     */
    @Override
    public void saveRefreshToken(String openId, RefreshToken token) {
        redisOps.setValue(refreshTokenKey(openId), token, token.getExpireIn(), TimeUnit.MILLISECONDS);
    }

    @Override
    public RefreshToken getRefreshToken(String openId) {
        return redisOps.getValue(refreshTokenKey(openId), RefreshToken.class);
    }

    @Override
    public void saveClientToken(ClientToken token) {
        redisOps.setValue(clientTokenKey(), token, token.getExpireIn(), TimeUnit.MILLISECONDS);
    }

    @Override
    public ClientToken getClientToken() {
        return redisOps.getValue(clientTokenKey(), ClientToken.class);
    }
}